package com.mmall.util;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by root on 18-5-5.
 */
public class CookieUitl {
    private static String SESSION_ID_COOKIE_DOMAIN = ".mmall.com";
    public static String SESSION_ID_COOKIE_NAME = "sessionid";


    public static  String readCookieValue(HttpServletRequest request, String cookieName) {
        Cookie ck = readCookie(request, cookieName);
        return ck == null ? null : ck.getValue();
    }

    public static Cookie readCookie (HttpServletRequest request, String cookieName) {
        if (request == null || StringUtils.isBlank(cookieName)) {
            return null;
        }
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0 && request != null) {
            for (Cookie ck : cookies) {
                if (cookieName.equalsIgnoreCase(ck.getName())) {
                    return ck;
                }
            }
        }
        return null;
    }

    public static int delCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) {
        if (request == null || response == null || StringUtils.isBlank(cookieName)) {
            return -1;
        }
        Cookie ck = readCookie(request, cookieName);
        ck.setMaxAge(0);
        response.addCookie(ck);
        return 1;
    }


    public static void writeSessionIdCookie(HttpServletResponse response, String sessionId) {
        if (!StringUtils.isBlank(sessionId) && response != null) {
            Cookie cookie = new Cookie(SESSION_ID_COOKIE_NAME, sessionId);
            cookie.setDomain(SESSION_ID_COOKIE_DOMAIN);
            cookie.setMaxAge(60 * 60 * 24 * 365);
            cookie.setPath("/");

            cookie.setHttpOnly(true);
            response.addCookie(cookie);
        }
    }

    public static String readSessionId(HttpServletRequest request) {
        return readCookieValue(request, SESSION_ID_COOKIE_NAME);
    }

    public static int delSessionIdCookie(HttpServletRequest request, HttpServletResponse response) {
        return delCookie(request, response, SESSION_ID_COOKIE_NAME);
    }

}